import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

import java.lang.reflect.Method;

/**
 * @Author: huangjc
 * @Date: Created in 2018/12/28 17:10
 */
public class Example3 {
    public static void main(String[] args) throws Exception {

        ClassPool pool = ClassPool.getDefault();

        //将Person类的字节码封装成一个CtClass
        CtClass ctClass = pool.get("entity.Person");

        // say 方法
        CtMethod ctMethod = ctClass.getDeclaredMethod("say");
        //占据第8行的代码，原有的第8行代码后移
        ctMethod.insertAt(8,"{System.out.println(\"====insertAt line 8====\");}");
        //添加到前面
        ctMethod.insertBefore("{System.out.println(\"====before====\");}");
        //添加到后面
        ctMethod.insertAfter("{System.out.println(\"====after====\");}");

        // eat 方法
        ctMethod = ctClass.getDeclaredMethod("eat");
        ctMethod.insertBefore("{System.out.println(\"insertBefore，今天伙食：\" + $1 + \"&\" + $2);}");
        ctMethod.insertAfter("System.out.println(\"insertAfter，\" + $1 + \"和\" + $2 + \"已经被我吃完了，哈哈\");");

        //创建对象
        Object obj = ctClass.toClass().newInstance();
        Method method = obj.getClass().getDeclaredMethod("say");
        method.invoke(obj);

        System.out.println();

        method = obj.getClass().getDeclaredMethod("eat", String.class, String.class);
        method.invoke(obj, "五常大米", "牛羊肉");
    }
}
